package org.miaosha.controller;

import org.miaosha.model.GoodsInfoView;
import org.miaosha.model.MiaoshaUser;
import org.miaosha.result.Result;
import org.miaosha.service.GoodsService;
import org.miaosha.service.MiaoshaUserService;
import org.miaosha.vo.LoginVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * @author Wrb
 * @date 2019/7/11 11:21
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

	private final static Logger log = LoggerFactory.getLogger(GoodsController.class);

	@Autowired
	private MiaoshaUserService userService;

	@Autowired
	private GoodsService goodsService;

	@RequestMapping("/to_list")
	public String list(Model model, MiaoshaUser user) {
		model.addAttribute("user", user);
		List<GoodsInfoView> goodsInfoList = goodsService.getGoodsInfoList();
		model.addAttribute("goodsList", goodsInfoList);
		return "goods_list";
	}

	@RequestMapping("/to_detail/{goodsId}")
	public String detail(Model model, MiaoshaUser user, @PathVariable Long goodsId) {
		model.addAttribute("user", user);
		GoodsInfoView goodsInfo = goodsService.getGoodsInfoById(goodsId);
		model.addAttribute("goods", goodsInfo);
		if (goodsInfo == null) {
			return "404";
		}
		long startAt = goodsInfo.getStartDate().getTime();
		long endAt = goodsInfo.getEndDate().getTime();
		long now = System.currentTimeMillis();

		int miaoshaStatus;
		int remainSeconds;

		if (now < startAt) { //秒杀还没开始 倒计时
			miaoshaStatus = 0;
			remainSeconds = (int) ((startAt - now)/1000);
		} else if (now > endAt) { //秒杀结束
			miaoshaStatus = 2;
			remainSeconds = -1;
		}else { //秒杀进行中
			miaoshaStatus = 1;
			remainSeconds = 0;
		}
		model.addAttribute("miaoshaStatus", miaoshaStatus);
		model.addAttribute("remainSeconds", remainSeconds);
		return "goods_detail";
	}

}